package middleware

import (
	"aiworkc/pkg/httpx"
	"aiworkc/pkg/token"
	"github.com/gin-gonic/gin"
	"strings"
)

type Jwt struct {
	tokenParser *token.Parse
}

func NewJwt(secret string) *Jwt {
	return &Jwt{
		tokenParser: token.NewTokenParse(secret),
	}
}

func (m *Jwt) Handler(ctx *gin.Context) {
	// 检查是否在白名单路径中
	if isWhitelistPath(ctx.Request.URL.Path) {
		ctx.Next()
		return
	}

	r, err := m.tokenParser.ParseWithContext(ctx.Request)
	if err != nil {
		httpx.FailWithErr(ctx, err)
		ctx.Abort()
		return
	}

	ctx.Request = r
	ctx.Next()
}

func isWhitelistPath(path string) bool {
	whitelist := []string{
		"/v1/user/login",
		"/v1/user",
	}

	for _, p := range whitelist {
		if strings.HasPrefix(path, p) {
			return true
		}
	}
	return false
}
